package cn.aj.exm.exception;


import cn.aj.exm.result.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
    * @Title: exceptionHandler
    * @Description: TODO
    * @Author: Mr.GT
    * @Version: 1.0
    * @Date:  2022/12/27 0027 21:26
    * @Parameters: [e]
    * @Return cn.aj.result.JsonResult
     * 捕捉自定义异常
    */
    @ExceptionHandler(GlobalException.class)
    public JsonResult exceptionHandler (GlobalException e) {
        e.printStackTrace();
        // 1.打印日志
        log.error("发生系统异常，异常信息为{}, {}", e.getMessage(), e.getCode());
        // 2.返回异常信息
        return JsonResult.error(e.getMessage(), e.getCode());
    }

    /**
    * @Title: exceptionHandler
    * @Description: TODO
    * @Author: Mr.GT
    * @Version: 1.0
    * @Date:  2022/12/27 0027 21:26
    * @Parameters: [e]
    * @Return cn.aj.result.JsonResult
     * 捕捉最大异常
    */
    @ExceptionHandler(Exception.class)
    public JsonResult exceptionHandler (Exception e) {
        e.printStackTrace();
        // 1.打印日志
        log.error("发生系统异常，异常信息为{}", e.getMessage());
        // 2.返回异常信息
        return JsonResult.error(GlobalExceptionEnum.ERROR.getMessage(), GlobalExceptionEnum.ERROR.getCode());
    }

    /**
    * @Title: exceptionHandler
    * @Description: TODO
    * @Author: Mr.GT
    * @Version: 1.0
    * @Date:  2022/12/27 0027 21:28
    * @Parameters: [e]
    * @Return cn.aj.result.JsonResult
     * 参数注解异常
    */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult methodArgumentNotValidException (MethodArgumentNotValidException e) {
        e.printStackTrace();
        // 1.打印日志
        log.error("发生系统异常，异常信息为{}", e.getMessage(), GlobalExceptionEnum.PARAMETER_VERIFICATION.getCode());
        // 2.返回异常信息
        StringBuilder stringBuilder = new StringBuilder();
        e.getBindingResult().getAllErrors().forEach(error->{
            stringBuilder.append(error.getDefaultMessage() + ";");});
        return JsonResult.error(stringBuilder.toString(), GlobalExceptionEnum.PARAMETER_VERIFICATION.getCode());
    }
}



